package com.example.chat.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.example.chat.domain.Group;
import com.example.chat.domain.GroupMember;
import com.example.chat.domain.GroupMessage;
import com.example.chat.domain.MessageDTO;
import com.example.chat.mapper.GroupMapper;
import com.example.chat.mapper.GroupMemberMapper;
import com.example.chat.mapper.GroupMessageMapper;
import com.example.chat.service.GroupService;
import com.example.common.core.constants.Constants;
import com.example.common.core.utils.ThreadLocalUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 群组服务实现类
 * 注：此实现为示例，实际项目中应该连接数据库并访问相应的Mapper
 */
@Service
public class GroupServiceImpl implements GroupService {
    private static final Logger logger = LoggerFactory.getLogger(GroupServiceImpl.class);
    
    @Autowired
    private GroupMapper groupMapper;
    
    @Autowired
    private GroupMemberMapper groupMemberMapper;
    
    @Autowired
    private GroupMessageMapper groupMessageMapper;
    
    @Override
    @Transactional
    public Long createGroup(Group group) {

        groupMapper.insert(group);
        Long userId = ThreadLocalUtil.get(Constants.USER_ID,Long.class);
        Long creatorId = userId;
        GroupMember creator = new GroupMember();
        creator.setGroupId(group.getGroupId());
        creator.setUserId(creatorId);
        creator.setNickname(ThreadLocalUtil.get(Constants.USER_NAME,String.class));
        creator.setIdentity(ThreadLocalUtil.get(Constants.USER_IDENTITY,Integer.class));
        groupMemberMapper.insert(creator);
        logger.info("创建群组: {}, ID: {}", group.getName(), group.getGroupId());
        return group.getGroupId();
    }

    @Override
    public Group getGroup(Long groupId) {
        LambdaQueryWrapper<Group> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Group::getGroupId, groupId)
                    .eq(Group::getDelFlag, 0);
        return groupMapper.selectOne(queryWrapper);
    }

    @Override
    @Transactional
    public boolean updateGroup(Group group) {
        LambdaQueryWrapper<Group> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Group::getGroupId, group.getGroupId())
                    .eq(Group::getDelFlag, 0);
        int result = groupMapper.update(group, queryWrapper);
        if (result > 0) {
            logger.info("更新群组: {}", group.getName());
            return true;
        }
        return false;
    }

    @Override
    @Transactional
    public boolean dissolveGroup(Long groupId, Long userId) {
        // 验证用户是否为群创建者
        LambdaQueryWrapper<GroupMember> memberQueryWrapper = new LambdaQueryWrapper<>();
        memberQueryWrapper.eq(GroupMember::getGroupId, groupId)
                          .eq(GroupMember::getUserId, userId)
                          .eq(GroupMember::getDelFlag, 0);
        
        if (groupMemberMapper.selectCount(memberQueryWrapper) == 0) {
            logger.warn("用户 {} 不是群组 {} 的成员，无法解散群组", userId, groupId);
            return false;
        }
        
        // 检查是否是创建者
        Group group = getGroup(groupId);
        if (group == null || !group.getCreateBy().equals(userId)) {
            logger.warn("用户 {} 不是群组 {} 的创建者，无法解散群组", userId, groupId);
            return false;
        }
        
        // 更新群组为已删除
        LambdaUpdateWrapper<Group> groupUpdateWrapper = new LambdaUpdateWrapper<>();
        groupUpdateWrapper.eq(Group::getGroupId, groupId)
                          .eq(Group::getDelFlag, 0)
                          .set(Group::getDelFlag, 1); // 标记为已删除
        
        int groupResult = groupMapper.update(null, groupUpdateWrapper);
        if (groupResult > 0) {
            // 更新所有成员状态为已删除
            LambdaUpdateWrapper<GroupMember> memberUpdateWrapper = new LambdaUpdateWrapper<>();
            memberUpdateWrapper.eq(GroupMember::getGroupId, groupId)
                              .eq(GroupMember::getDelFlag, 0)
                              .set(GroupMember::getDelFlag, 1); // 标记为已删除
            
            groupMemberMapper.update(null, memberUpdateWrapper);
            
            logger.info("解散群组: {}", group.getName());
            return true;
        }
        
        return false;
    }

    @Override
    @Transactional
    public boolean addGroupMember(GroupMember groupMember) {
        // 检查群组是否存在
        Group group = getGroup(groupMember.getGroupId());
        if (group == null) {
            logger.warn("群组 {} 不存在或已删除", groupMember.getGroupId());
            return false;
        }
        
        // 检查用户是否已经是群成员
        LambdaQueryWrapper<GroupMember> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(GroupMember::getGroupId, groupMember.getGroupId())
                   .eq(GroupMember::getUserId, groupMember.getUserId())
                   .eq(GroupMember::getDelFlag, 0);
        
        if (groupMemberMapper.selectCount(queryWrapper) > 0) {
            logger.warn("用户 {} 已经是群组 {} 的成员", groupMember.getUserId(), groupMember.getGroupId());
            return false;
        }
        
        // 保存群成员
        int result = groupMemberMapper.insert(groupMember);
        
        if (result > 0) {
            logger.info("添加群成员: 群组ID={}, 用户ID={}", groupMember.getGroupId(), groupMember.getUserId());
            return true;
        }
        return false;
    }

    @Override
    public List<GroupMember> getGroupMembers(Long groupId) {
        LambdaQueryWrapper<GroupMember> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(GroupMember::getGroupId, groupId)
                   .eq(GroupMember::getDelFlag, 0);
        return groupMemberMapper.selectList(queryWrapper);
    }

    @Override
    @Transactional
    public boolean removeGroupMember(Long groupId, Long userId, Long operatorId) {
        // 检查群组是否存在
        Group group = getGroup(groupId);
        if (group == null) {
            logger.warn("群组 {} 不存在或已删除", groupId);
            return false;
        }
        
        // 检查操作者是否为群创建者
        if (!group.getCreateBy().equals(operatorId)) {
            logger.warn("用户 {} 不是群组 {} 的创建者，无法移除成员", operatorId, groupId);
            return false;
        }
        
        // 更新成员为已删除
        LambdaUpdateWrapper<GroupMember> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(GroupMember::getGroupId, groupId)
                    .eq(GroupMember::getUserId, userId)
                    .eq(GroupMember::getDelFlag, 0)
                    .set(GroupMember::getDelFlag, 1); // 标记为已删除
        
        int result = groupMemberMapper.update(null, updateWrapper);
        if (result > 0) {
            logger.info("移除群成员: 群组ID={}, 用户ID={}", groupId, userId);
            return true;
        }
        
        logger.warn("用户 {} 不是群组 {} 的成员", userId, groupId);
        return false;
    }

    @Override
    @Transactional
    public boolean quitGroup(Long groupId, Long userId) {
        // 检查群组是否存在
        Group group = getGroup(groupId);
        if (group == null) {
            logger.warn("群组 {} 不存在或已删除", groupId);
            return false;
        }
        
        // 群创建者不能退出群组，必须先解散群组
        if (group.getCreateBy().equals(userId)) {
            logger.warn("群创建者 {} 不能直接退出群组，必须先解散群组", userId);
            return false;
        }
        
        // 更新成员为已删除
        LambdaUpdateWrapper<GroupMember> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(GroupMember::getGroupId, groupId)
                    .eq(GroupMember::getUserId, userId)
                    .eq(GroupMember::getDelFlag, 0)
                    .set(GroupMember::getDelFlag, 1); // 标记为已删除
        
        int result = groupMemberMapper.update(null, updateWrapper);
        if (result > 0) {
            logger.info("退出群组: 群组ID={}, 用户ID={}", groupId, userId);
            return true;
        }
        
        logger.warn("用户 {} 不是群组 {} 的成员", userId, groupId);
        return false;
    }

    @Override
    @Transactional
    public GroupMessage saveGroupMessage(MessageDTO messageDTO) {
        Long senderId = ThreadLocalUtil.get(Constants.USER_ID,Long.class);
        String senderName = ThreadLocalUtil.get(Constants.USER_NAME,String.class);
        // 检查群组是否存在
        Group group = getGroup(messageDTO.getGroupId());
        if (group == null) {
            logger.warn("群组 {} 不存在或已删除", messageDTO.getGroupId());
            return null;
        }
        // 检查发送者是否是群成员
        LambdaQueryWrapper<GroupMember> memberQueryWrapper = new LambdaQueryWrapper<>();
        memberQueryWrapper.eq(GroupMember::getGroupId, messageDTO.getGroupId())
                         .eq(GroupMember::getUserId, senderId)
                         .eq(GroupMember::getDelFlag, 0);
        if (groupMemberMapper.selectCount(memberQueryWrapper) == 0) {
            logger.warn("用户 {} 不是群组 {} 的成员，无法发送消息", senderId, messageDTO.getGroupId());
            return null;
        }
        // 保存消息
        GroupMessage message = new GroupMessage();
        message.setGroupId(messageDTO.getGroupId());
        message.setSenderId(senderId);
        message.setSenderName(senderName);
        message.setContent(messageDTO.getContent());
        message.setStatus(0); // 0-正常
        groupMessageMapper.insert(message);
        logger.info("保存群组消息: 群组ID={}, 发送者ID={}", message.getGroupId(), message.getSenderId());
        return message;
    }

    @Override
    public List<GroupMessage> getGroupMessages(Long groupId, Integer offset, Integer limit) {
        // 检查群组是否存在
        Group group = getGroup(groupId);
        if (group == null) {
            logger.warn("群组 {} 不存在或已删除", groupId);
            return new ArrayList<>();
        }
        
        List<GroupMessage> groupMessages = groupMessageMapper.selectGroupMessages(groupId, offset, limit);
        Long userId = ThreadLocalUtil.get(Constants.USER_ID, Long.class);

        // 使用流式处理优化消息发送者ID的调整
        return groupMessages.stream()
                .peek(message -> message.setSenderId(
                        message.getSenderId().equals(userId) ? 0L : 1L
                ))
                .collect(java.util.stream.Collectors.toList());
    }

    @Override
    @Transactional
    public boolean recallMessage(Long messageId, Long userId) {
        // 查找消息
        LambdaQueryWrapper<GroupMessage> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(GroupMessage::getId, messageId)
                   .eq(GroupMessage::getStatus, 0)
                   .eq(GroupMessage::getDelFlag, 0);
        
        GroupMessage message = groupMessageMapper.selectOne(queryWrapper);
        
        if (message == null) {
            logger.warn("消息 {} 不存在或已被撤回", messageId);
            return false;
        }
        
        // 检查是否是发送者本人
        if (!message.getSenderId().equals(userId)) {
            logger.warn("用户 {} 不是消息 {} 的发送者，无法撤回", userId, messageId);
            return false;
        }
        
        // 检查消息发送时间是否在2分钟内（假设只能撤回2分钟内的消息）
        long messageTime = message.getCreateTime().toInstant(java.time.ZoneOffset.of("+8")).toEpochMilli();
        long currentTime = System.currentTimeMillis();
        if (currentTime - messageTime > 2 * 60 * 1000) {
            logger.warn("消息 {} 发送时间已超过2分钟，无法撤回", messageId);
            return false;
        }
        
        // 更新消息状态为已撤回
        LambdaUpdateWrapper<GroupMessage> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(GroupMessage::getId, messageId)
                    .set(GroupMessage::getStatus, 1); // 1-已撤回

        int result = groupMessageMapper.update(null, updateWrapper);
        if (result > 0) {
            logger.info("撤回消息: 消息ID={}, 用户ID={}", messageId, userId);
            return true;
        }
        
        return false;
    }
} 